import { Component } from 'react'
import Taro from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import './index.scss'
import global from '../../global';
import { Button, Map, Textarea, Input, Image } from '@tarojs/components'
import Request from '../../api/index'
import Utils from '../../utils'
import Event from '../../event';

export default class Index extends Component {

  constructor() {
    super();
    this.state = {
      form: {
        name: '',
        address: '',
        attachment: '',
        content: '',
        phone: '',
        userId: '',
      },
      loading: false,
      editable: true,
      isEventDetail: false,
      processes: [],
      statusMap: {
        '0': {
          label: '待处理',
          color: '#f1a63f'
        },
        '1': {
          label: '处理中',
          color: '#479bfe'
        },
        '2': {
          label: '处理完成',
          color: 'green'
        }
      }
    }
    this.submitForm = this.submitForm.bind(this);
    this.loadProcess = this.loadProcess.bind(this);
  }

  componentWillMount () {
    if (global.isEventDetail) {
      this.loadProcess();
      this.setState({
        editable: false,
        form: global.currentRepairEvent,
        isEventDetail: true
      })
    }
  }

  componentDidMount () {}

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  validateForm(form) {

    if (!form.name) {
      Taro.showToast({
        title: '请输入报修人姓名！',
        icon: "error",
        duration: 1000
      });
      return false;
    }
    if (!form.phone) {
      Taro.showToast({
        title: '请输入联系方式！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.address) {
      Taro.showToast({
        title: '请输入报修地址！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.attachment) {
      Taro.showToast({
        title: '请上传相关问题招聘！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.content) {
      Taro.showToast({
        title: '请输入报修内容！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    return true;
  }

  async submitForm() {
    if (this.state.loading) {
      return;
    }
    this.state.loading = true;
    this.setState({
      loading: true
    })
    let { form } = this.state;
    if (!this.validateForm(form)) {
      this.setState({
        loading: false
      });
      return;
    }
    form.userId = global.userInfo.userId;
    form.wxUserName = global.userInfo.userName;
    form.villageId = global.userInfo.bindingVillageId;
    form.villageName = global.userInfo.bindingVillageName;
    form.status = '0';
    try {
      let res = await Request.post('/business/repair_events', form);
      console.log(res)
      if (res.data.code !== 200) {
        throw new Error();
      }
      await Taro.navigateBack();
      await Taro.showToast({
        title: '提交成功！',
        icon: "success",
        duration: 1000
      });
      Event.emit('updateRepairEvent')
    } catch (e) {
      await Taro.showToast({
        title: '提交失败请重试',
        icon: "error",
        duration: 1000
      })
    } finally {
      this.setState({
        loading: false
      });
    }

  }

  async uploadImg() {
    try {
      let res = await Taro.chooseImage();
      await Taro.showLoading({
        title: '上传中'
      });
      let uploadFileRes = await Taro.uploadFile({
        url: Request.host + '/common/upload',
        filePath: res.tempFilePaths[0],
        name: 'file',
        header: {
          'Authorization': global.token
        },
        success: async (res) => {
          console.log(res, 'sss')
          let data = JSON.parse(res.data)
          if (data.code !== 200) {
            throw new Error();
          }
          if (!this.state.form.attachment) {
            this.state.form.attachment = data.fileName;
          } else {
            this.state.form.attachment += `,${data.fileName}`;
          }
          this.setState({
            form: this.state.form
          })
          await Taro.hideLoading();
          await Taro.showToast({
            title: '上传成功！',
            type: 'success'
          })
        }
      });
    } catch (e) {
      console.log("上传文件失败")
    } finally {
      await Taro.hideLoading();
    }
  }

  async loadProcess() {
    try {
      let res = await Request.get(`/business/review_info/list?businessId=${global.currentRepairEvent.eventId}&reviewType=REPAIR_EVENT`);
      if (res.data.code === 200) {
        this.setState({
          processes: res.data.rows
        })
      }
    } catch (e) {
      console.log("获取流程信息失败")
    }
  }


  render () {
    let { form, loading, editable, isEventDetail, processes, statusMap} = this.state;

    let attachments = form.attachment.split(',');

    let msg = '请填入以下信息进行报修';

    if (isEventDetail) {
      msg = global.currentRepairEvent.status === '2' ? '报修处理完成，感谢您的反馈' : '已反馈到物业，请等候处理'
    }

    return (
      <View className='repair_report_container'>
        <View className='auth_msg_container'>
          <Text className='msg_container color-blue'>{msg}</Text>
        </View>
        <View className='input_item'>
          <Text className='required'>报修人</Text>
          <Input disabled={!editable} value={form.name} onInput={(e) => {this.setState({form: {...form, name: e.detail.value}})}} type='text' placeholder='请输入您的姓名'/>
        </View>
        <View className='input_item'>
          <Text className='required'>联系方式</Text>
          <Input disabled={!editable} value={form.phone} onInput={(e) => {this.setState({form: {...form, phone: e.detail.value}})}} type='text' placeholder='请输入您的联系方式'/>
        </View>
        <View className='input_item'>
          <Text className='required'>报修地址</Text>
          <Input disabled={!editable} value={form.address} onInput={(e) => {this.setState({form: {...form, address: e.detail.value}})}} type='text' placeholder='请输入报修地址'/>
        </View>
        <View className='input_item'>
          <Text className='required'>报修内容</Text>
          <Textarea disabled={!editable} value={form.content} onInput={(e) => {this.setState({form: {...form, content: e.detail.value}})}} type='text' placeholder='请输入报修内容'/>
        </View>
        <View className='input_item'>
          <Text className='required'>报修图片</Text>
          {/*<Input disabled={!editable} value={form.address} onInput={(e) => {this.setState({form: {...form, address: e.detail.value}})}} type='text' placeholder='请输入公司地址'/>*/}
          <View className='img-upload'>
            <View className='img_upload_container'>
              {
                form.attachment && attachments.map(item => <Image className='image_container' src={Request.imgHost + item}/>)
              }
              {
                editable && attachments.length < 3 && <View className='image_container' onClick={this.uploadImg.bind(this)}>
                  <Text className='iconfont icon-add size50 cars_list'/>
                </View>
              }
            </View>
            {
              editable && <Text className='size28 tips'>最多支持上传3张图片</Text>
            }
          </View>
        </View>
        {
          editable && <Button loading={loading} className='submit_btn' type='primary' onClick={this.submitForm}>上报</Button>
        }
        {
          editable && <View className='tips'>
            <Text className='iconfont icon-tanhao size40'/>
            <Text className='size28'> 提交申请后，物业会尽快进行处理</Text>
          </View>
        }
        {
          isEventDetail && (
            <View>
              <Text>处理流程</Text>
              <View className='process_container'>
                {
                  processes.length > 0 ?
                    processes.map(item => {
                      let original = statusMap[item.originalStatus];
                      let dest = statusMap[item.destStatus];
                      return (
                        <View className='process_item'>
                          <View>
                            <Text style={original}>{original.label}</Text>
                            <Text> -> </Text>
                            <Text style={dest}>{dest.label}</Text>
                          </View>
                          <Text>{item.reviewContent}</Text>
                          <Text>{item.createTime}</Text>
                        </View>
                      )
                    })
                    :
                    <Text>物业尚未进行处置，请等候...</Text>
                }
              </View>
            </View>
          )
        }
      </View>
    )
  }
}
